package net.dreamlu.iot.mqtt.broker.http;

import lombok.RequiredArgsConstructor;
import net.dreamlu.iot.mqtt.broker.enums.RedisKeys;
import net.dreamlu.iot.mqtt.broker.model.PlayTimeDto;
import net.dreamlu.iot.mqtt.broker.service.IMqttBrokerService;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import net.dreamlu.iot.mqtt.core.server.http.api.MqttHttpRoute;
import net.dreamlu.iot.mqtt.core.server.http.api.result.Result;
import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: chenlf
 * @date: 2023/9/5
 * @description: EndpointsHttpApi
 **/
@Component
@RequiredArgsConstructor
public class PlayAllTimeHttpApi implements MqttHttpRoute, SmartInitializingSingleton {

    private final IMqttBrokerService mqttBrokerService;
    private MqttServerCreator serverCreator;
    private final ApplicationContext context;
    private final MicaRedisCache redisCache;

    @Override
    public String path() {
        return "/api/v1/playAllTime";
    }

    @Override
    public HttpResponse invoke(HttpRequest request) {
        String key = RedisKeys.CONNECT_PLAYE_TIME.getKey(serverCreator.getNodeName());
        Set<String> keys = redisCache.keys(key + "*");
        List<PlayTimeDto> collect = keys.stream().map(k -> {
            String playTime = redisCache.get(k);
            PlayTimeDto playTimeDto = new PlayTimeDto();
            playTimeDto.setStartTime(playTime);
            playTimeDto.setClientId(k.replace(key + ":", ""));
            return playTimeDto;
        }).collect(Collectors.toList());
        return Result.ok(request, collect);
    }

    @Override
    public void afterSingletonsInstantiated() {
        this.serverCreator = context.getBean(MqttServerCreator.class);
    }
}
